import { Component, ElementRef, Renderer2 } from '@angular/core';
import { ApesField } from './apes-field';
import { ApiService } from '@core/services/http/api.service';
import { Events } from '@core/services/events/Events';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { SubjectService } from '@core/services/events/subject.service';
import { agCurrency, agNumber, formatNumber } from '../../../../utils/utils';
import { ENTER } from '@angular/cdk/keycodes';

@Component({
  selector: 'formly-field-input',
  template: `
    <apes-input-number style="width:100%" [formControl]="formControl" [formlyAttributes]="field"
                       [apesPlaceHolder]="to.placeholder"
                       [apesDisabled]="to.disabled"
                       [apesMin]="to.min"
                       [apesMax]="to.max"
                       [apesFormatter]="formatterValue"
                       (keydown)="onKeyDown($event)"
                       [apesPrecision]="precision"></apes-input-number>
  `,
})
export class FormlyFieldInputNumber extends ApesField {
  formatterValue = (value) => {
    if (value == null) value = 0;
    if (this.to.hasOwnProperty('valueFormatter')) {
      if (this.to.valueFormatter == 'currency') {
        return '￥' + formatNumber(value, 2);
      } else if (this.to.valueFormatter == 'percent') {
        return formatNumber(value, 2) + '%';
      } else if (this.to.valueFormatter == 'number') {
        return formatNumber(value, 2);
      }
    } else {
      return value;
    }
  };

  constructor(protected apiService: ApiService, protected events: Events, protected expressionService: ExpressionService, protected subject: SubjectService,
              protected elementRef: ElementRef, protected renderer: Renderer2) {
    super(apiService, events, expressionService, subject);
  }

  ngOnInit(): void {
    this.addDefalutPlaceholder('请输入');
    this.addEventListener(this.elementRef, this.renderer);
  }

  get precision() {
    return this.to.precision ? Number(this.to.precision) : 2;
  }

  get readonly() {
    return this.to.readonly;
  }

  onKeyDown(event): void {
    // let key = event.which || event.keyCode;
    if (event.keyCode === ENTER) {
      event.preventDefault();
      event.stopPropagation();
    }
  }

}
